//
//  BaseVoiceManager.swift
//  Fitness
//
//  Created by MacBook Pro on 2021/9/10.
//

import UIKit
import AVFoundation

let voiceManager: BaseVoiceManager = BaseVoiceManager()

class BaseVoiceManager: NSObject {

    let voiceLanguage: String = "com.apple.ttsbundle.siri_female_zh-CN_compact"
    var isSuspend: Bool = false

    private var currentDayModel: EveryDayTrainingModel? = nil
    private var currentTrainingModel: TrainingModel? = nil
    private lazy var speechSynth: AVSpeechSynthesizer = {
        let speechSynth = AVSpeechSynthesizer()
        speechSynth.delegate = self
        return speechSynth
    }()
    
    ///结束
    func lg_finishedRespeech() {
            speechSynth.stopSpeaking(at: .word)//停止播放，调用这个方法，再开始时会从头开始重新朗读
        }
        
    ///暂停
    func lg_pauseSpeech() {
        speechSynth.pauseSpeaking(at: .word)//停止播放，调用这个方法，再开始时会从头开始重新朗读
    }
    
    
    func play(text: String) {
        let utterance = AVSpeechUtterance(string: "如果上天再给我一次机会,我一定会对她说我爱你!")
        utterance.rate = 0.4  // 设置语速，范围0-1，注意0最慢，1最快；
        let speechVoice = AVSpeechSynthesisVoice(language:voiceLanguage)
        utterance.voice = speechVoice //设置语速
        utterance.volume = 0.9;//设置音量
        utterance.pitchMultiplier = 1.0 // 声音的音调 0.5f～2.0f
        utterance.preUtteranceDelay = 0.0 //播放下下一句话的时候有多长时间的延迟 Default is 0.0
        utterance.postUtteranceDelay = 0.0 //开始播放之前需要等待多久 Default is 0.0
        speechSynth.speak(utterance)
    }
    
    func loopTraining(currentDayModel: EveryDayTrainingModel) -> Void {
        if (self.currentDayModel!.trainingGroupArray.count != 0) {
            var groupModel = self.currentDayModel!.trainingGroupArray[0]
            if (groupModel.trainingArray.count != 0) {
                let trainingModel = groupModel.trainingArray[0];
                self.currentTrainingModel = trainingModel
                var utterance = AVSpeechUtterance(string: "第\(groupModel.id)组 第\(trainingModel.id)节 \(trainingModel.actionName) \(trainingModel.actionTimes)次")
                utterance.rate = 0.5  // 设置语速，范围0-1，注意0最慢，1最快；
                var speechVoice = AVSpeechSynthesisVoice(language:voiceLanguage)
                utterance.voice = speechVoice //设置语速
                utterance.volume = 0.9;//设置音量
//                speechVoice?.quality = enhanced;
                utterance.pitchMultiplier = 1.0 // 声音的音调 0.5f～2.0f
                utterance.preUtteranceDelay = 0.5 //播放下下一句话的时候有多长时间的延迟 Default is 0.0
                utterance.postUtteranceDelay = 0.0 //开始播放之前需要等待多久 Default is 0.0
                speechSynth.speak(utterance)
                for i in 0..<Int(trainingModel.actionTimes)! {
                    utterance = AVSpeechUtterance(string: "\(i+1)")
                    utterance.rate = 0.2  // 设置语速，范围0-1，注意0最慢，1最快；
                    speechVoice = AVSpeechSynthesisVoice(language:voiceLanguage)
                    utterance.voice = speechVoice //设置语速
                    utterance.volume = 0.9;//设置音量
                    utterance.pitchMultiplier = 1.0 // 声音的音调 0.5f～2.0f
                    utterance.preUtteranceDelay = 0.0 //播放下下一句话的时候有多长时间的延迟 Default is 0.0
                    utterance.postUtteranceDelay = 0.0 //开始播放之前需要等待多久 Default is 0.0
                    speechSynth.speak(utterance)
                }
                groupModel.trainingArray.remove(at: 0)
                if groupModel.trainingArray.count == 0 {
                    if self.currentDayModel?.trainingGroupArray.count == 1 {
                        utterance = AVSpeechUtterance(string: "今天的训练到此结束，你很棒")
                    } else {
                        utterance = AVSpeechUtterance(string: "第\(groupModel.id)组训练完成，继续加油")
                    }
                } else {
                    utterance = AVSpeechUtterance(string: "休息一下吧")
                }
                utterance.rate = 0.5  // 设置语速，范围0-1，注意0最慢，1最快；
                speechVoice = AVSpeechSynthesisVoice(language:voiceLanguage)
                utterance.voice = speechVoice //设置语速
                utterance.volume = 0.9;//设置音量
                utterance.pitchMultiplier = 1.0 // 声音的音调 0.5f～2.0f
                utterance.preUtteranceDelay = 0.0 //播放下下一句话的时候有多长时间的延迟 Default is 0.0
                utterance.postUtteranceDelay = 0.0 //开始播放之前需要等待多久 Default is 0.0
                speechSynth.speak(utterance)
            } else {
                self.currentDayModel?.trainingGroupArray.remove(at: 0)
            }
            
            self.currentDayModel!.trainingGroupArray[0] = groupModel
        }
    }
    
    func playWithModel(currentDayModel: EveryDayTrainingModel) -> Void {
        if self.isSuspend {
            speechSynth.continueSpeaking();
        } else {
            self.isSuspend = false;
            if self.currentDayModel?.id == currentDayModel.id {
                return;
            }
            self.currentDayModel = currentDayModel
            let utterance = AVSpeechUtterance(string: "训练开始 一共\(currentDayModel.trainingGroupArray.count)组动作")
            utterance.rate = 0.5  // 设置语速，范围0-1，注意0最慢，1最快；
            let speechVoice = AVSpeechSynthesisVoice(language:voiceLanguage)
            utterance.voice = speechVoice //设置语速
            utterance.volume = 0.9;//设置音量
            utterance.pitchMultiplier = 1.0 // 声音的音调 0.5f～2.0f
            utterance.preUtteranceDelay = 0.0 //播放下下一句话的时候有多长时间的延迟 Default is 0.0
            utterance.postUtteranceDelay = 0.0 //开始播放之前需要等待多久 Default is 0.0
            speechSynth.speak(utterance)
            loopTraining(currentDayModel: currentDayModel)
        }


    }
    func suspendSpeech() -> Void {
        self.isSuspend = true
        speechSynth.pauseSpeaking(at: AVSpeechBoundary.immediate);
//        speechSynth.pauseSpeaking(at: AVSpeechBoundaryImmediate);
    }
    func stopSpeech() -> Void {
        self.isSuspend = false
        speechSynth.stopSpeaking(at: AVSpeechBoundary.immediate)
        self.currentDayModel = nil
    }
}

extension BaseVoiceManager: AVSpeechSynthesizerDelegate {
    func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didStart utterance: AVSpeechUtterance) {
        print("开始")
    }
    func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didFinish utterance: AVSpeechUtterance) {
        print("结束")
        if utterance.speechString.contains("休息一下吧") {
            
            DispatchQueue.main.asyncAfter(deadline: .now()+DispatchTimeInterval.seconds(Int(self.currentTrainingModel!.restTime)!)) {
                self.loopTraining(currentDayModel: self.currentDayModel!);
            }
        } else if utterance.speechString.contains("今天的训练到此结束，你很棒") {
            self.currentDayModel = nil
        }
    }
    func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didCancel utterance: AVSpeechUtterance) {
        print("取消")
    }
}

